package com.peanut.baby.mvp.calendar;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.db.DBManager;
import com.peanut.baby.model.CalendarRecord;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.calendar.decorators.IconDecorator;
import com.peanut.baby.mvp.calendar.decorators.TextColorDecorator;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.tencent.mars.xlog.Log;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/12.
 */

public class CalendarDisplayActivity extends BaseMvpActivity
        implements TitleLayout.OnTitleClickListener,
        OnDateSelectedListener{
    private static final String TAG = CalendarDisplayActivity.class.getSimpleName();
    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.calendar_view)
    MaterialCalendarView calendarView;
    @BindView(R.id.tongfang)
    TextView tongfang;
    @BindView(R.id.tiwen)
    TextView tiwen;
    @BindView(R.id.yesuan)
    TextView yesuan;
    @BindView(R.id.baidai)
    TextView baidai;
    @BindView(R.id.dayima)
    TextView dayima;


    private String date = "";
    public static void start(Context ctx,String date) {
        ctx.startActivity(new Intent(ctx, CalendarDisplayActivity.class).putExtra("date",date));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar_display);
        ButterKnife.bind(this);
        date = getIntent().getStringExtra("date");
        initView();

        reDecoratCalendarWhenDataChanged();
        resetAndDisplayDateOfDate(date);
    }

    private void initView() {
        title.setTitle("记录");
        title.setOnTitleClickedListener(this);
        calendarView.setOnDateChangedListener(this);

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
        Log.d(TAG, "onDateSelected " + selected + " " + date.toString());
        resetAndDisplayDateOfDate(CalUtil.dateToString(date.getDate()));

    }

    /**
     * 重置所有数据后展示某一天的数据
     * @param date
     */
    private void resetAndDisplayDateOfDate(String date){
        Log.d(TAG,"resetAndDisplayDateOfDate "+date);
        calendarView.setSelectedDate(CalUtil.stringToDate(date));
        calendarView.setCurrentDate(CalendarDay.from(CalUtil.stringToDate(date)));

        resetAllValuesWhenDateChanged();
        displayDataOfDate(date);
    }

    /**
     * 重置所有数据
     */
    private void resetAllValuesWhenDateChanged(){
        dayima.setText("");
        tongfang.setText("");
        tiwen.setText("");
        yesuan.setText("");
        baidai.setText("");
    }

    /**
     * 展示某一天的数据
     * @param _date
     */
    private void displayDataOfDate(String _date){
        CalendarRecord record = DBManager.getInstance().getCalendarRecord(Integer.parseInt(InitManager.getInstance().getUserId()),_date);
        if(record != null){
            dayima.setText(record.dayima);

            tongfang.setText(record.tongfang);

            tiwen.setText(record.tiwen);

            yesuan.setText(record.yesuan);

            baidai.setText(record.baidai);

        }
    }

    /**
     * 数据改变后重新加载数据
     */
    private void reDecoratCalendarWhenDataChanged(){

        List<CalendarRecord> records = DBManager.getInstance().getAllCalendarRecord(Integer.parseInt(InitManager.getInstance().getUserId()));
        if(records == null || records.isEmpty()){
            return;
        }
        calendarView.removeDecorators();
        Collections.sort(records);

        ArrayList<CalendarDay> menseStartArray = new ArrayList<>();
        ArrayList<CalendarDay> menseEndArray = new ArrayList<>();
        ArrayList<CalendarDay> recordArray = new ArrayList<>();

        //test
        for(int i=0;i<records.size();i++){
            final CalendarRecord record = records.get(i);
            Log.d(TAG,"record "+i+" "+record.toString());
            if(!StringUtil.isNullOrEmpty(record.dayima)){
                if(record.dayima.equals(AppConfig.StringConstants.MENSE_COME)){

                    menseStartArray.add(CalendarDay.from(CalUtil.stringToDate(record.date)));

                    Log.d(TAG,"\t大姨妈来了"+i+" "+record.toString());
                    CalendarRecord goRecord = getRecentMenseGoRecord(i,records);
                    Log.d(TAG,"\t最近的大姨妈走的时间"+(goRecord == null? " 没有记录 ":goRecord.toString()));

                    //判断如果没有月经走了 要计算一个默认值
                    if(goRecord == null){
                        Date[] period = CalUtil.getYuejingPeriodWithYuejingStartDate(record.date);
                        if(period != null){
                            menseEndArray.add(CalendarDay.from(period[1]));
                        }
                    }else{
                        menseEndArray.add(CalendarDay.from(CalUtil.stringToDate(goRecord.date)));
                    }


                    reCalculatePeriods(CalUtil.stringToDate(record.date),goRecord == null? null:CalUtil.stringToDate(goRecord.date));


                }else{
                    //大姨妈走了
                    menseEndArray.add(CalendarDay.from(CalUtil.stringToDate(record.date)));
                }

            }else{
                //有记录标示
                recordArray.add(CalendarDay.from(CalUtil.stringToDate(record.date)));
            }

        }

        //
        calendarView.addDecorator(new IconDecorator(CalendarCache.getMenseStartBitmap(), menseStartArray));
        calendarView.addDecorator(new IconDecorator(CalendarCache.getMenseEndBitmap(), menseEndArray));
        calendarView.addDecorator(new IconDecorator(CalendarCache.getHasRecordBitmap(), recordArray));
    }

    /**
     *
     * @param index
     * @param source
     * @return
     */
    private CalendarRecord getRecentMenseGoRecord(int index,List<CalendarRecord> source){
        if(source == null || source.isEmpty()){
            return null;
        }

        if(index <0 || index >source.size()-1){
            return null;
        }
        for(int i = index+1;i<source.size();i++){
            final CalendarRecord record = source.get(i);
            if(!StringUtil.isNullOrEmpty(record.dayima)){
                if(record.dayima.equals(AppConfig.StringConstants.MENSE_COME)){
                    Log.i(TAG,"\t两个来了挨着 直接返回null"+i+" "+record.toString());
                    //两个来了挨着
                    return null;
                }
                if(record.dayima.equals(AppConfig.StringConstants.MENSE_GO)){
                    Log.i(TAG,"\t最近的选项"+i+" "+record.toString());
                    int daysDiff = CalUtil.daysBetween(record.date,source.get(index).date);
                    if(Math.abs(daysDiff) > 10){
                        return null;
                    }else{
                        return record;
                    }
                }

            }

        }
        return null;
    }

    private void reCalculatePeriods(Date menseStartDate,Date menseEndDate) {
        Date[] period = CalUtil.getPregnantPeriodWithYuejingStartDate(menseStartDate);
        Date pailuan = CalUtil.getPailuanDay(menseStartDate);

        Date[] yuejingPeriod = null;
        if(menseEndDate != null){
            yuejingPeriod = new Date[2];
            yuejingPeriod[0] = menseStartDate;
            yuejingPeriod[1] = menseEndDate;
        }else{
            //根据默认月经天数计算
            yuejingPeriod = CalUtil.getYuejingPeriodWithYuejingStartDate(menseStartDate);
        }


        displayMensePeriod(yuejingPeriod);
        displayPailuanDate(pailuan);
        displayPregnantablePeriod(period);
    }

    /**
     * 画经期
     * @param period
     */
    private void displayMensePeriod(Date[] period){
        Log.d(TAG,"displayMensePeriod: "+(period == null? "period not define":CalUtil.dateToString(period[0])+"-"+CalUtil.dateToString(period[1])));
        Calendar calendar = Calendar.getInstance();
        //画月经预测期
        if (period != null) {
            ArrayList<CalendarDay> periodArray = new ArrayList<>();
            int d = CalendarCache.getYuejingColor();

            calendar.setTime(period[0]);
            int days = CalUtil.daysBetweenPlusOne(period[0], period[1]);
            for (int i = 0; i < days; i++) {
                CalendarDay day = CalendarDay.from(calendar);
                periodArray.add(day);
                calendar.add(Calendar.DATE, 1);
            }
            calendarView.addDecorator(new TextColorDecorator(d, periodArray));
        }

    }

    /**
     * 画排卵日
     * @param pailuanDate
     */
    private void displayPailuanDate(Date pailuanDate){
        Log.d(TAG,"displayPailuanDate: "+(pailuanDate == null? "date not define":CalUtil.dateToString(pailuanDate)));
        if (pailuanDate != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(pailuanDate);
            CalendarDay pailuanDay = CalendarDay.from(calendar);
            ArrayList<CalendarDay> pailuanArray = new ArrayList<>();
            pailuanArray.add(pailuanDay);

            Bitmap bit = CalendarCache.getPailuanBitmap();

            calendarView.addDecorator(new IconDecorator(bit, pailuanArray));

        }
    }

    /**
     * 画易孕期
     * @param period
     */
    private void displayPregnantablePeriod(Date[] period){
        Log.d(TAG,"displayPregnantablePeriod: "+(period == null? "period not define":CalUtil.dateToString(period[0])+"-"+CalUtil.dateToString(period[1])));
        if (period != null) {
            Calendar calendar = Calendar.getInstance();
            //画易孕日
            ArrayList<CalendarDay> periodArray = new ArrayList<>();
            int d = CalendarCache.getYiyunColor();

            calendar.setTime(period[0]);
            int days = CalUtil.daysBetweenPlusOne(period[0], period[1]);
            for (int i = 0; i < days; i++) {
                CalendarDay day = CalendarDay.from(calendar);
                periodArray.add(day);
                calendar.add(Calendar.DATE, 1);
            }
            calendarView.addDecorator(new TextColorDecorator(d, periodArray));
        }
    }

}
